﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.IO;
using System.Web.Core;

namespace Yuanlin.Business
{
    public class CompanyBrandAddControl : YuanlinUserControl
    {
        protected ValuedTextBox titleValuedTextBox;
        protected ValuedEditor descriptionValuedEditor;

        protected HtmlInputFile attachmentData;
        protected IButton SaveButton;
        protected IButton BackButton;
        private YuanlinUser user = HttpContext.Current.User as YuanlinUser;

        protected override void OnLoad(EventArgs e)
        {
            SaveButton.Click += new EventHandler(SaveButton_Click);
            BackButton.Click += new EventHandler(BackButton_Click);
        }

        public void BackButton_Click(object sender, EventArgs e)
        {
            PageRedirect();
        }

        public void SaveButton_Click(object sender, EventArgs e)
        {
            CompanyBrand companyBrand = new CompanyBrand();

            companyBrand.Title.Value = CensorWordManager.CensorWord(this.titleValuedTextBox.Value);
            companyBrand.UserId.Value = user.EntityId.Value;
            companyBrand.Body.Value = CensorWordManager.CensorWord(this.descriptionValuedEditor.Value);
            companyBrand.CreateDate.Value = DateTime.Now;

            if (BusinessManager.CreateCompanyBrand(companyBrand) == -2)
            {
                Globals.ShowMessage(this.Page, "添加失败", "此信息已经存在！");
                return;
            }

            if (SiteUrls.Instance().IsAttachmentValid(attachmentData))
            {
                companyBrand.AttachmentFileName.Value = SiteUrls.Instance().GetPostedFileName(attachmentData);
                BusinessManager.UpdateCompanyBrand(companyBrand);
                SiteUrls.Instance().SaveFile(SiteUrls.Instance().GetFile(companyBrand), attachmentData);
            }

            if (string.IsNullOrEmpty(user.CompanyBrand))
            {
                user.CompanyBrand = "1";
            }
            else
            {
                user.CompanyBrand = (Int32.Parse(user.CompanyBrand) + 1).ToString();
            }
            UserManager.UpdateUser(user);

            PageRedirect();
        }
        private void PageRedirect()
        {
            Page.Response.Redirect(SiteUrls.Instance().GetCompanyBrandListUrl());
        }
    }
}